package com.alex.config;

import com.alex.dao.Person;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Random;

/**
 * 请求体拦截器
 */
@RestControllerAdvice
public class ConsumerRequestBodyAdvise implements RequestBodyAdvice {

    /**
     * 判断哪些方法需要被拦截
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> convertType) {
        return methodParameter.getParameterAnnotation(ProcessTag.class) != null;
    }

    /**
     * 读取请求体之前的处理
     */
    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        return httpInputMessage;
    }

    /**
     * 读取请求体之后的处理
     */
    @Override
    public Object afterBodyRead(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        if (body instanceof Person) {
            Person person = (Person) body;
            return new Person(person.getId(), person.getName().toUpperCase() + "Advise", person.getAge());
        }

        return body;
    }

    /**
     * 请求体为空时的处理
     */
    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        if (Person.class.isAssignableFrom((Class<?>) type)) {
            return new Person(new Random().nextLong(), "NoBody", -1);
        }

        return body;
    }
}
